package com.koron.common.web.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.koron.bean.base.BaseBean;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.business.system.feign.SystemFeignService;
import com.koron.common.core.business.weather.bean.QWeatherBean;
import com.koron.common.core.business.weather.bean.QWeatherDto;
import com.koron.common.core.business.weather.bean.WeatherBean;
import com.koron.common.core.business.weather.bean.WeatherDto;
import com.koron.common.core.business.weather.mapper.QWeatherBeanMapper;
import com.koron.common.core.business.weather.mapper.WeatherBeanMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CommonUtils;
import com.koron.common.core.util.ExportExcelUtil;
import com.koron.common.core.util.FastJsonUtils;
import com.koron.common.core.util.HttpClient;
import com.koron.common.core.util.qywx.QywxUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Api(tags = "公共接口")
@Slf4j
@RestController
@RequestMapping("/CommonCon")
@CrossOrigin
public class CommonController {

    private EamUser getEamUser() {
        return ThreadLocalContext.get();
    }

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }


    @Autowired
    private SystemFeignService systemfeignservice;

    @Autowired
    private QywxUtil qywxUtil;

    private static final String URL = "https://restapi.amap.com/v3/weather/weatherInfo?";
    private static final String QURL = "https://devapi.qweather.com/v7/weather/now";

    @ApiOperation(value = "获取高德天气")
    @GetMapping("/getweather")
    public Response<WeatherDto.LivesDTO> getAddress(@RequestParam("city") String city) {
        WeatherBean weatherBean = ADOConnection.runTask(sessionFactory -> sessionFactory.getMapper(WeatherBeanMapper.class).findOneByCity(city), WeatherBean.class);

        Assert.isFalse(weatherBean == null, "不存在城市");

        Map<String, String> configmap = ConfigInfoTool.getConfigByCode("common", "weather");
        String eamGd = configmap.get("eam_gd_gsjsc");


        HttpClient httpClient = new HttpClient();
        Map<String, String> map = new HashMap<>();
        map.put("key", eamGd);
        map.put("city", weatherBean.getAdcode());
        map.put("extensions", "base");
        map.put("output", "JSON");
        String s = httpClient.doGet(URL, map);
        WeatherDto jsonToBean = FastJsonUtils.getJsonToBean(s, WeatherDto.class);
        return Response.ok(jsonToBean.getLives().get(0));
    }

    @ApiOperation(value = "获取和风天气")
    @GetMapping("/getQweather")
    public Response<QWeatherDto.NowDTO> getQweather(@RequestParam("city") String city) {

        QWeatherBean qweather = ADOConnection.runTask(sessionFactory -> sessionFactory.getMapper(QWeatherBeanMapper.class).findOneByLocationNameZh(city), QWeatherBean.class);

        Assert.isFalse(qweather == null, "不存在城市");

        Map<String, String> configmap = ConfigInfoTool.getConfigByCode("common", "weather");
        String eamHf = configmap.get("eam_hf_gsjsc");

        HttpClient httpClient = new HttpClient();
        Map<String, String> map = new HashMap<>();
        map.put("key", eamHf);
        map.put("location", qweather.getLocationId());
        map.put("lang", "zh");

        String s = null;
        try {
            s = httpClient.getResponse(QURL, HttpMethod.GET, map, getHeaderParams());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        log.info(s);
        QWeatherDto jsonToBean = FastJsonUtils.getJsonToBean(s, QWeatherDto.class);
        jsonToBean.getNow().setCityStr(qweather.getLocationNameZh());
        return Response.ok(jsonToBean.getNow());
    }

    public Map<String, String> getHeaderParams() {
        Map<String, String> headerparams = new HashMap<>();
        headerparams.put("Content-Type", "application/json;charset=UTF-8");
        headerparams.put("Connection", "keep-alive");
        headerparams.put("Content-Encoding", "gzip");

        return headerparams;
    }

    /**
     * 下载设备导入错误表格
     * @return
     */
    @ApiOperation("---下载设备导入错误表格")
    @GetMapping("/errorEqExport")
    public void errorExport(@RequestParam(value = "filename") String filename, HttpServletResponse response) {
        log.info("导入错误信息路径"+ filename);
        try {
            String[] names = filename.split(",");
            if (names.length == 1) {
                String path = ExportExcelUtil.getLocationPath(names[0]);
                HttpClient.downLoadCommon(response, FileUtil.file(path), filename);
                return;
            }
        } catch (Exception e) {
            log.error("下载导入错误信息异常");
            log.error(e.getMessage(), e);
        }
    }

    @GetMapping("/getPowersss")
    @ApiOperation(value = "获取无权限组织列表")
    public Response<String> getPowersss() {
        return ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), factory->{
            List<String> power = CommonUtils.getPower(getEamUser());
            List<OrgBean> ok = CommonUtils.ok(systemfeignservice.queryNextOrgList(new OrgBean()));
            List<String> allorg = ok.stream().map(BaseBean::getId).collect(Collectors.toList());
            return Response.success(CollUtil.disjunction(allorg, power));
        }, Response.class);
    }


    @ApiOperation("企业微信通过agentConfig注入应用的权限")
    @GetMapping("/getJsTicket")
    public Response<String> getJsApiTicket(){
        String ticket = qywxUtil.getJsTicket();
        if (StrUtil.isNotBlank(ticket)){
            return Response.ok(ticket);
        }
        return Response.fail("获取企业微信jsTicket失败！");
    }

}
